import 'package:auto_route/annotations.dart';
import 'package:distribution_mall_flutter/assets.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/pages/address/address_search/application/address_search_service.dart';
import 'package:distribution_mall_flutter/pages/address/address_search/search_address_provider.dart';
import 'package:easy_debounce/easy_debounce.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../../widgets/bottom_sheet_appbar.dart';

class AddressSearchPage extends StatefulHookConsumerWidget{
  const AddressSearchPage({super.key});

  @override
  ConsumerState<AddressSearchPage> createState() => _AddressSearchPageState();
}

class _AddressSearchPageState extends ConsumerState<AddressSearchPage> {
  @override
  Widget build(BuildContext context) {
    ref.watch(addressSearchServiceProvider);
    var searchTextEditingController = useTextEditingController();
    return SizedBox(
      height: MediaQuery.of(context).size.height * 0.8,
      child: Column(
        children: [
          Container(
            margin: const EdgeInsets.only(left: 24, right: 24),
            padding: const EdgeInsets.only(top: 26),
            child: Consumer(builder: (context, ref, _) {
              var isLoading = ref.watch(searchAddressIsLoadingProvider);
              return BottomSheetAppbar(
                title: isLoading
                    ? '${S.current.select_region}(${S.current.loading})'
                    : S.current.select_region,
              );
            }),
          ),
          Container(
            margin:
                const EdgeInsets.only(bottom: 16, top: 24, left: 24, right: 24),
            padding: const EdgeInsets.only(left: 11),
            height: 30,
            decoration: BoxDecoration(
              color: const Color(0xFFE6E6EA),
              borderRadius: BorderRadius.circular(24),
            ),
            child: Row(
              children: [
                const Icon(
                  Icons.search,
                  color: Color(0xfF868D96),
                  size: 20,
                ),
                Expanded(
                  child: Container(
                    margin: const EdgeInsets.only(left: 9),
                    child: TextField(
                      controller: searchTextEditingController,
                      style: const TextStyle(fontSize: 14, color: Colors.black),
                      decoration: InputDecoration(
                        hintText: S.current.select_region_hint,
                        isDense: true,
                        contentPadding: EdgeInsets.zero,
                        enabledBorder: InputBorder.none,
                        focusedBorder: InputBorder.none,
                        border: InputBorder.none,
                      ),
                      autofocus: true,
                      inputFormatters: [
                        LengthLimitingTextInputFormatter(10),
                      ],
                      onChanged: (str) {
                        EasyDebounce.debounce(
                            'AddressSearchPage',
                            // <-- An ID for this particular debouncer
                            const Duration(milliseconds: 200),
                            // <-- The debounce duration
                            () {
                          if (str.length >= 3) {
                            ref
                                .read(addressSearchServiceProvider)
                                .queryAddressByName(str,searchTextEditingController);
                          }
                          debugPrint(str);
                        });
                      },
                    ),
                  ),
                )
              ],
            ),
          ),
          const Divider(),
          Expanded(child: Consumer(builder: (_, ref, __) {
            var data = ref.watch(searchAddressProvider);
            return ListView.builder(
                itemBuilder: (_, index) {
                  var item = data![index];
                  String name = item.firstAddress?.name ?? '';
                  return ListTile(
                    title: Text(
                      name,
                      style: const TextStyle(fontSize: 16, color: Colors.black),
                    ),
                    leading: Image.asset(
                      Assets.assets_icons_search_position_png,
                      width: 24,
                    ),
                    subtitle: item.secondAddress != null
                        ? Text(
                            '${formatName(item.secondAddress?.name, item.thirdAddress != null)}${formatName(item.thirdAddress?.name, item.fourthAddress != null)}${item.fourthAddress?.name ?? ''}',
                            style: const TextStyle(
                                fontSize: 14, color: Color(0xFF868D96)))
                        : null,
                    onTap: () {
                      Navigator.pop(context, item);
                    },
                  );
                },
                itemCount: data?.length ?? 0);
          }))
        ],
      ),
    );
  }

  String formatName(String? name, bool hasNext) {
    if (name == null) {
      return '';
    } else {
      return '$name${hasNext ? ',' : ''}';
    }
  }
}
